// 连续5个才成功
const judgeNum = 5

function judgeWin(squares, x, y) {
  // 取出行和列
  let win = false
  // 判断每一行
  let list1 = squares[y].filter(it=>it)
  win = win || judgeWinLine(list1)
  // 判断每一列
  let list2 = squares.map((it, index) => it[x]).filter(it=>it)
  win = win || judgeWinLine(list2)

  let list3 = findDiagonal(squares,x,y).filter(it=>it)
  win = win || judgeWinLine(list3)

  let list4 = findDiagonal(squares,x,y,true).filter(it=>it)
  win = win || judgeWinLine(list4)
  return win
}

// 判断是否成功
function judgeWinLine(lines) {
  return continuousString(lines) >= judgeNum
}
// 获取对角线
function findDiagonal(squares,x,y,flag){
  let yLen = squares.length
  let xLen = squares[0].length
  let result = []
  
  for (let yIndex = 0; yIndex < yLen; yIndex++) {
    let xIndex = x - y + yIndex
    if(flag){
      xIndex = x + y - yIndex
    }
    if( xIndex>0 && xIndex < xLen){
      result.push(squares[yIndex][xIndex])
    }
  }
  return result
}


// 找出连续的最大字符串
function continuousString(str) {
  let finalObj = {}
  let tempObj = {}
  let count = 0
  for (let i = 0; i < str.length; i++) {
    const code = str[i]
    if (code === str[i + 1]) {  // 初次时候，两个相等
      if (!tempObj[code]) {
        tempObj[code] = 2       // 初次时候，两个相等就加 2
      } else {
        tempObj[code] += 1      // 后面相等加 1
      }
    } else {
      if (!finalObj[code]) {    // 不相等情况
        finalObj[code] = 1      // 自己加 1
      }
      if (finalObj[code] < tempObj[code]) { // 和临时存储的数值进行对比，如果小于，则进行赋值
        finalObj[code] = tempObj[code]
      }
      tempObj[code] = 0         // 设置为 0，因为连续相等这个条件已经断开了
    }
  }
  for (const key in finalObj) {
    const item = finalObj[key]
    if (count < item) {
      count = item
    }
  }
  return count
}

export { judgeWin }